package ucap.com.lesanapp.activitys;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import butterknife.Bind;
import butterknife.ButterKnife;
import ucap.com.lesanapp.R;
import ucap.com.lesanapp.bean.NewContentData;
import ucap.com.lesanapp.bean.NewsDetailedBean;
import ucap.com.lesanapp.global.Constants;
import ucap.com.lesanapp.global.SettingsModelState;
import ucap.com.lesanapp.utils.NetworkStateUtils;
import ucap.com.lesanapp.utils.PrefUtils;

public class NewsDetailedActivity extends Activity implements View.OnClickListener {
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.wv_content)
    WebView webView;
    @Bind(R.id.ll_load)
    LinearLayout llLoading;
    @Bind(R.id.btn_text_size)
    Button btnTextSize;
    @Bind(R.id.btn_share)
    ImageButton btnShare;
    private Intent intent;
    private WebSettings setting;
    private int model;
    private int networkType;
    private String code;
    private int textSize;
    private String cid;
    public NewContentData newContentData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detailed);
        Log.i("activityTest", "onCreate");
        ButterKnife.bind(this);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getType();
        intent = getIntent();
        String title = intent.getStringExtra("title");
        code = intent.getStringExtra("code");
        cid = intent.getStringExtra("cid");
        tvTitle.setText(title);
        btnTextSize.setOnClickListener(this);
        btnShare.setOnClickListener(this);
        getServiceDates();
    }

    /**
     * 判断网络网络环境以及,阅读模式
     */
    public void getType() {
        model = PrefUtils.getInt("model", SettingsModelState.MODEL_TEXT_AND_IMAGE, this);
        Log.i("model", model + "模式");
        networkType = NetworkStateUtils.network(this);
        Log.i("model", networkType + "网络状态");
    }

    /**
     * 解析json,并解析副文本
     *
     * @param result
     */

    private void analysisDate(String result) {
        Log.i("detailedUrl", result);
        Gson gson = new Gson();
        newContentData = gson.fromJson(result, NewContentData.class);
        setting = webView.getSettings();
        setting.setJavaScriptEnabled(true);
        setting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        setting.setRenderPriority(WebSettings.RenderPriority.HIGH); //提高渲染速度
        //判断浏览模式
        if (model == SettingsModelState.MODEL_TEXT_AND_IMAGE) {
            //图文模式
            setting.setBlockNetworkImage(false);
        } else if (model == SettingsModelState.MODEL_TEXT) {
            //文本模式
            setting.setBlockNetworkImage(true);
        } else if (model == SettingsModelState.MODEL_AUTOMATIC) {
            //智能模式
            if (networkType == ConnectivityManager.TYPE_WIFI) {
                setting.setBlockNetworkImage(false);
            } else {
                setting.setBlockNetworkImage(true);
            }
        }
        setting.setUseWideViewPort(true);//关键点
        setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setting.setLoadWithOverviewMode(true);

        //获取选择的字体大小
        textSize = PrefUtils.getInt("newsDetailedTextSize", 1, this);
        setting.setTextZoom(setTextSize(textSize));
        webView.addJavascriptInterface(new JavascriptInterface(NewsDetailedActivity.this), "imagelistner");
        webView.addJavascriptInterface(new JavascriptVideoInterface(NewsDetailedActivity.this), "videolistner");
        webView.loadUrl(newContentData.getUrl());
        webView.setWebViewClient(new WebViewClient() {
            //网页开始加载
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.i("webView", "网页开始加载");
                llLoading.setVisibility(View.VISIBLE);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i("webView", "网页跳转");
                view.loadUrl(url);
                return true;

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i("webView", "网页加载结束");
                llLoading.setVisibility(View.GONE);
                webView.loadUrl("javascript:(function(){"
                        + "var objs=document.getElementsByTagName(\"img\");"
                        + "for(var i=0;i<objs.length;i++){"
                        + "     window.imagelistner.imagsUrl(objs[i].src);"
                        + "      objs[i].onclick=function(){"
                        + "          window.imagelistner.openImage(this.src)"
                        + " }"
                        + "}"
                        + "})()");
                webView.loadUrl("javascript:(function(){"
                        + "var objs=document.getElementsByTagName(\"video\");"
                        + "for(var i=0;i<objs.length;i++){"
                        + "     window.videolistner.videoUrl(objs[i].src);"
                        + "      objs[i].onclick=function(){"
                        + "          window.videolistner.openVideo(this.src)"
                        + " }"
                        + "}"
                        + "})()");

            }
        });


    }

    //
    ArrayList<String> imageUri;

    /**
     * 根据选择的字体设置字体大小
     *
     * @param wh
     * @return
     */
    public int setTextSize(int wh) {
        switch (wh) {
            case 0://小号
                return 80;
            case 1://默认
                return 120;
            case 2://大号
                return 160;
            case 3://最号
                return 200;
        }
        return 300;
    }

    //js注入接口定义,方法名对应js方法名(解析后自动调用)
    private class JavascriptInterface {
        public JavascriptInterface(Context context) {
        }

        @android.webkit.JavascriptInterface
        public void openImage(final String img) {
            Log.i("image", "img" + img);
            Intent intent = new Intent(NewsDetailedActivity.this, ImageActivity.class);
            intent.putStringArrayListExtra("uris", imageUri);
            int position = 0;
            /**
             * 根据用户点击的地址判断点击的第几张
             */
            for (int i = 0; i < imageUri.size(); i++) {
                if (imageUri.get(i).equals(img)) {

                    position = i;
                }
            }
            intent.putExtra("position", position);
            startActivity(intent);

        }


        @android.webkit.JavascriptInterface
        public void imagsUrl(String img) {
            if (imageUri == null) {
                imageUri = new ArrayList<>();
            }
            imageUri.add(img);
        }


    }

    private class JavascriptVideoInterface {

        public JavascriptVideoInterface(Context context) {

        }

        @android.webkit.JavascriptInterface
        public void openVideo(String video) {
            Uri uri = Uri.parse(video);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "video/*");
            startActivityForResult(intent, 0);

        }

        @android.webkit.JavascriptInterface
        public void videoUrl(String video) {
            Log.i("vidoUri", video);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String cache = PrefUtils.getString("newsDetailed", "", NewsDetailedActivity.this);
        if (!cache.isEmpty()) {
            analysisDate(cache);
        }
        Log.i("result", "重新加载视频");
    }

    /**
     * 服务器获取内容
     */
    private void getServiceDates() {
        String url = Constants.URL_CONTENT + "?manuscriptid=" + code + "&&cid=" + cid;
        Log.i("newContentUri", url);

        HttpUtils utils = new HttpUtils();
        utils.send(HttpMethod.GET, url, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.i("newContent", responseInfo.result);
                analysisDate(responseInfo.result);
                PrefUtils.putString("newsDetailed", responseInfo.result, NewsDetailedActivity.this);
            }

            public void onFailure(HttpException error, String msg) {
                Toast.makeText(getApplicationContext(), "网络异常!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
        try {
            MobclickAgent.onPause(this);//友盟统计
        } catch (Exception e) {
        }

    }

    @Override
    public void onClick(View v) {
        if (v == btnTextSize) {
            String[] text = {"小号", "默认", "大号", "最大号"};
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("请选择文本大小属性:");
            final int[] temp = {1};
            int which = PrefUtils.getInt("newsDetailedTextSize", 1, this);
            dialog.setSingleChoiceItems(text, which, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    temp[0] = which;
                    Log.i("which", which + "文字编号--" + "设置的文字大小" + setTextSize(which));
                    PrefUtils.putInt("newsDetailedTextSize", which, NewsDetailedActivity.this);
                }
            });
            dialog.setNegativeButton("取消", null);
            dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    setting.setTextZoom(setTextSize(temp[0]));
                }
            });
            dialog.show();
        } else if (v == btnShare) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_TEXT, newContentData.getUrl());
            intent.setType("text/plain");
            startActivity(Intent.createChooser(intent, "分享到"));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            webView.onResume();
        } catch (Exception e) {
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.reload();
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);//解决播放网页视频,关闭后仍有声音的系统BUG
                return false;
            }
        });
    }

}
